<?php
// 处理AJAX请求
if (isset($_POST['action']) && $_POST['action'] === 'get_tables') {
    session_start();
    require_once 'crypto.php';
    
    // 检查用户是否已登录
    if (!isset($_SESSION['username'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '未登录']);
        exit();
    }

    // 获取数据库连接信息
    $db_id = isset($_POST['id']) ? $_POST['id'] : null;
    $data_file = 'db.json';
    $db_info = null;

    if ($db_id && file_exists($data_file)) {
        $encrypted_data = file_get_contents($data_file);
        $items = Crypto::decrypt($encrypted_data) ?? [];
        foreach ($items as $item) {
            if ($item['id'] == $db_id) {
                $db_info = $item;
                break;
            }
        }
    }

    header('Content-Type: application/json');
    
    try {
        if (!$db_info) {
            throw new Exception('数据库信息不存在 (ID: ' . $db_id . ')');
        }

        $dsn = "mysql:host={$db_info['address']};dbname={$db_info['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $db_info['username'], $db_info['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 5
        ]);
        $pdo->exec('set names utf8mb4');
        
        // 获取所有表名
        $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
        
        // 获取每个表的详细信息
        $tables_info = [];
        foreach ($tables as $table) {
            $tables_info[] = [
                'name' => $table
            ];
        }
        
        echo json_encode(['success' => true, 'tables' => $tables_info]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit();
}

// 新增：获取单表结构、记录数和部分数据
if (isset($_POST['action']) && $_POST['action'] === 'get_table_detail') {
    session_start();
    require_once 'crypto.php';
    if (!isset($_SESSION['username'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '未登录']);
        exit();
    }
    $db_id = $_POST['id'] ?? null;
    $table = $_POST['table'] ?? null;
    $data_file = 'db.json';
    $db_info = null;
    if ($db_id && file_exists($data_file)) {
        $encrypted_data = file_get_contents($data_file);
        $items = Crypto::decrypt($encrypted_data) ?? [];
        foreach ($items as $item) {
            if ($item['id'] == $db_id) {
                $db_info = $item;
                break;
            }
        }
    }
    header('Content-Type: application/json');
    try {
        if (!$db_info) throw new Exception('数据库信息不存在');
        if (!$table) throw new Exception('未指定表名');
        $dsn = "mysql:host={$db_info['address']};dbname={$db_info['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $db_info['username'], $db_info['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 5
        ]);
        $pdo->exec('set names utf8mb4');
        $columns = $pdo->query("SHOW COLUMNS FROM `$table`")->fetchAll(PDO::FETCH_ASSOC);
        $count = $pdo->query("SELECT COUNT(*) FROM `$table`")->fetchColumn();
        $data = $pdo->query("SELECT * FROM `$table` LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'columns' => $columns, 'count' => $count, 'data' => $data]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit();
}

// SQL执行接口
if (isset($_POST['action']) && $_POST['action'] === 'exec_sql') {
    session_start();
    require_once 'crypto.php';
    if (!isset($_SESSION['username'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '未登录']);
        exit();
    }
    $db_id = $_POST['id'] ?? null;
    $sql = trim($_POST['sql'] ?? '');
    $data_file = 'db.json';
    $db_info = null;
    if ($db_id && file_exists($data_file)) {
        $encrypted_data = file_get_contents($data_file);
        $items = Crypto::decrypt($encrypted_data) ?? [];
        foreach ($items as $item) {
            if ($item['id'] == $db_id) {
                $db_info = $item;
                break;
            }
        }
    }
    header('Content-Type: application/json');
    try {
        if (!$db_info) throw new Exception('数据库信息不存在');
        if (!$sql) throw new Exception('SQL语句不能为空');
        if (!preg_match('/^select\s/i', $sql)) throw new Exception('只允许执行SELECT语句');
        $dsn = "mysql:host={$db_info['address']};dbname={$db_info['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $db_info['username'], $db_info['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 10
        ]);
        $pdo->exec('set names utf8mb4');
        $stmt = $pdo->query($sql);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $result, 'columns' => $result ? array_keys($result[0]) : []]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit();
}

// --- 新增：处理CSV导出请求 ---
if (isset($_GET['action']) && $_GET['action'] === 'export_csv') { // 使用GET方便URL构建
    session_start();
    require_once 'crypto.php';
    
    // 1. 检查登录
    if (!isset($_SESSION['username'])) {
        header("HTTP/1.1 403 Forbidden");
        echo '未登录';
        exit();
    }

    // 2. 获取数据库信息
    $db_id = $_GET['id'] ?? null;
    $sql = trim($_GET['sql'] ?? ''); // 从GET获取SQL
    $data_file = 'db.json';
    $db_info = null;
    // ... (省略获取 $db_info 的代码，与 exec_sql 部分相同) ...
    if ($db_id && file_exists($data_file)) {
        $encrypted_data = file_get_contents($data_file);
        $items = Crypto::decrypt($encrypted_data) ?? [];
        foreach ($items as $item) {
            if ($item['id'] == $db_id) {
                $db_info = $item;
                break;
            }
        }
    }

    // 加载字典
    $dictionary = [];
    if (file_exists('dictionary.json')) {
        $dictionary = json_decode(file_get_contents('dictionary.json'), true) ?? [];
    }
    // 辅助函数：转换字段名
    // Ensure this function exists or define it here if needed globally
    if (!function_exists('translateFieldNamePhp')) {
        function translateFieldNamePhp($fieldName, $dictionary) {
            // 特殊处理别名
            if ($fieldName === 'total_num') return '总采集数量';
            if ($fieldName === 'total_ng_num') return '总不良数量';
            // 使用字典
            return $dictionary['fields'][$fieldName] ?? $fieldName;
        }
    }
    // 辅助函数：转换工厂代码
    if (!function_exists('translateFactoryCodePhp')) {
        function translateFactoryCodePhp($code, $dictionary) {
            return $dictionary['factory_codes'][$code] ?? $code;
        }
    }

    try {
        if (!$db_info) throw new Exception('数据库信息不存在');
        if (!$sql) throw new Exception('SQL语句不能为空');
        if (!preg_match('/^select\s/i', $sql)) throw new Exception('只允许执行SELECT语句');

        // 3. 连接数据库并执行查询
        $dsn = "mysql:host={$db_info['address']};dbname={$db_info['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $db_info['username'], $db_info['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_TIMEOUT => 10 // 导出可能耗时稍长
        ]);
        $pdo->exec('set names utf8mb4');
        $stmt = $pdo->query($sql);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($results)) {
             // 可以选择下载一个空文件或提示无数据
             // 这里简单地结束
             echo '<script>alert("没有数据可以导出"); window.close();</script>'; // 尝试用JS提示
             exit();
        }

        // 4. 设置CSV Header
        $filename = "export_" . $db_info['db_name'] . "_" . date('YmdHis') . ".csv";
        header('Content-Type: text/csv; charset=utf-8'); // 指定UTF-8编码
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        // BOM for UTF-8 Excel compatibility
        echo "\xEF\xBB\xBF"; 

        // 5. 打开输出流并写入CSV数据
        $output = fopen('php://output', 'w');

        // 写入表头 (使用翻译后的名称)
        $headers = array_keys($results[0]);
        $translated_headers = array_map(function($h) use ($dictionary) {
            return translateFieldNamePhp($h, $dictionary);
        }, $headers);
        fputcsv($output, $translated_headers);

        // 写入数据行
        foreach ($results as $row) {
            $output_row = [];
            foreach ($headers as $header) { // 按表头顺序取值
                 $value = $row[$header];
                 // 特殊处理工厂代码转换
                 if ($header === 'factory_no' && isset($dictionary['factory_codes'])) {
                     $value = translateFactoryCodePhp($value, $dictionary);
                 }
                 // 特殊处理 rate 列，如果存在则添加 % 符号
                 if ($header === 'rate' && $value !== null) {
                    $value .= '%';
                 }
                 $output_row[] = $value;
            }
            fputcsv($output, $output_row);
        }

        fclose($output);

    } catch (Exception $e) {
        // 导出失败处理
        header("HTTP/1.1 500 Internal Server Error");
        // 可以记录错误日志
        error_log("Export failed: " . $e->getMessage());
        echo '<script>alert("导出失败: ' . addslashes($e->getMessage()) . '"); window.close();</script>'; // 尝试用JS提示
    }
    // 6. 结束执行
    exit();
}
// --- 结束处理CSV导出请求 ---


// 如果不是AJAX请求或导出请求，继续处理普通页面请求
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

require_once 'crypto.php';

// 加载字典文件
$dictionary = [];
if (file_exists('dictionary.json')) {
    $dictionary = json_decode(file_get_contents('dictionary.json'), true) ?? [];
}

// 获取数据库连接信息
$db_id = isset($_GET['id']) ? $_GET['id'] : null;
$data_file = 'db.json';
$db_info = null;

if ($db_id && file_exists($data_file)) {
    $encrypted_data = file_get_contents($data_file);
    $items = Crypto::decrypt($encrypted_data) ?? [];
    foreach ($items as $item) {
        if ($item['id'] == $db_id) {
            $db_info = $item;
            break;
        }
    }
}

// 如果找不到数据库信息，返回列表页
if (!$db_info) {
    header("Location: index.php");
    exit();
}

// 确保函数定义在HTML输出前
if (!function_exists('mask_middle')) {
    function mask_middle($str) {
        $len = mb_strlen($str);
        if ($len <= 4) return str_repeat('*', $len);
        $start = mb_substr($str, 0, 2);
        $end = mb_substr($str, -2);
        return $start . str_repeat('*', $len - 4) . $end;
    }
}

// The following two function definitions are JavaScript and should be removed from the PHP block.
// function translateFieldName(fieldName) { ... }
// function scrollToTop() { ... }

?>
<!DOCTYPE html>
<html>
<head>
    <title>数据库查询 - <?php echo htmlspecialchars($db_info['name']); ?></title>
    <meta charset="UTF-8">
    <!-- 移除flatpickr相关引入，恢复原生日期时间选择器 -->

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 96vw;
            width: 100%;
            min-width: 600px;
            margin: 30px auto;
            background: white;
            padding: 32px 32px 20px 32px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .db-info {
            background-color: #fafafa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .db-info p {
            margin: 5px 0;
        }
        .db-info strong {
            display: inline-block;
            width: 80px;
        }
        .back-btn {
            color: #1677ff;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
        }
        .back-btn:hover {
            text-decoration: underline;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #eee;
            position: relative;
            z-index: 2;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            user-select: none;
            position: relative;
            z-index: 2;
        }
        .tab.active {
            border-bottom-color: #1677ff;
            color: #1677ff;
        }
        .tab-content {
            display: none;
            position: relative;
            z-index: 1;
        }
        .tab-content.active {
            display: block;
        }
        .sql-editor {
            width: 100%;
            height: 200px;
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: monospace;
            resize: vertical;
        }
        .execute-btn {
            background-color: #1677ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        .execute-btn:hover {
            background-color: #4096ff;
        }
        .result-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            table-layout: fixed;
            border: 1px solid #ddd;
            position: relative;
            z-index: 1;
        }
        .result-table th, .result-table td {
            padding: 4px;
            border: 1px solid #ddd;
            font-size: 14px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            background-color: #fff;
        }
        .result-table th {
            background-color: #fafafa;
            position: sticky;
            top: 0;
            z-index: 1;
            font-size: 15px;
            font-weight: bold;
        }
        .table-list {
            margin-top: 20px;
        }
        .table-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            padding: 15px;
            cursor: pointer;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }
        .table-header {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 10px;
        }
        .table-name {
            font-weight: bold;
            font-size: 16px;
        }
        .table-detail {
            margin-top: 10px;
            display: none;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error-message {
            color: #ff4d4f;
            padding: 10px;
            background: #fff2f0;
            border: 1px solid #ffccc7;
            border-radius: 4px;
            margin: 10px 0;
        }
        .table-count {
            color: #666;
            margin-left: 20px;
        }
        .table-item.active .table-name {
            color: #1677ff;
            font-weight: bold;
            background: #e6f4ff;
            border-radius: 4px;
            padding: 2px 6px;
        }
        /* 悬浮返回首页按钮 */
        .float-back-btn {
            position: fixed;
            right: 32px;
            top: 32px;
            z-index: 999;
            background: #1677ff;
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 14px 28px;
            font-size: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.12);
            cursor: pointer;
            transition: background 0.2s;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .float-back-btn:hover {
            background: #4096ff;
        }
        /* 返回顶部按钮样式 */
        .back-to-top {
            position: fixed;
            right: 32px;
            bottom: 32px;
            z-index: 999;
            background: #1677ff;
            color: #fff;
            border: none;
            border-radius: 50%;
            width: 48px;
            height: 48px;
            font-size: 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.12);
            cursor: pointer;
            transition: all 0.3s;
            display: none;
            align-items: center;
            justify-content: center;
            text-decoration: none;
        }
        .back-to-top:hover {
            background: #4096ff;
            transform: translateY(-2px);
        }
        .back-to-top.visible {
            display: flex;
        }
        /* 时间选择器样式 */
        .datetime-input {
            width: 160px !important;
            min-width: 140px !important;
            max-width: 200px !important;
            box-sizing: border-box;
            background: #fff !important;
            border: 1px solid #ccc !important;
        }
        .datetime-input::-webkit-calendar-picker-indicator {
            /* 恢复默认，不做任何限制，保证弹窗正常 */
        }
        .datetime-input::-webkit-inner-spin-button,
        .datetime-input::-webkit-clear-button {
            display: none;
        }
        .datetime-input::-webkit-datetime-edit {
            padding: 0;
        }
        .datetime-input::-webkit-datetime-edit-fields-wrapper {
            padding: 0;
        }
        .datetime-input::-webkit-datetime-edit-text {
            padding: 0;
        }
        .datetime-input::-webkit-datetime-edit-year-field,
        .datetime-input::-webkit-datetime-edit-month-field,
        .datetime-input::-webkit-datetime-edit-day-field,
        .datetime-input::-webkit-datetime-edit-hour-field,
        .datetime-input::-webkit-datetime-edit-minute-field,
        .datetime-input::-webkit-datetime-edit-second-field {
            padding: 0;
        }
        .factory-summary {
            background-color: #e6f4ff !important;
        }
        .factory-summary td {
            padding: 8px 4px;
            border: 1px solid #ddd;
            background-color: #e6f4ff !important;
        }
        .rate-cell {
            color: #52c41a;
        }
        /* 新增：表格行悬停高亮效果 */
        .result-table tbody tr:hover {
            background-color: #e6f4ff !important; /* 使用浅蓝色高亮，!important确保覆盖其他背景色 */
            cursor: pointer; /* 可选：改变鼠标指针样式 */
        }
        /* 新增：确保汇总行的悬停效果也能覆盖其自身的背景色 */
        .result-table tbody tr.factory-summary:hover {
            background-color: #cce5ff !important; /* 使用一个稍深一点的蓝色来区分普通行 */
        }

        /* --- 数据查询表单美化 --- */
        .query-form {
            /* background-color: #fafafa; */ /* 可选：添加轻微背景 */
            /* border: 1px solid #eee; */   /* 可选：添加边框 */
            /* padding: 20px; */           /* 可选：添加内边距 */
            /* border-radius: 8px; */      /* 可选：添加圆角 */
        }

        .query-form .form-group {
            margin-bottom: 20px; /* 增加表单组之间的垂直间距 */
            display: flex;       /* 使用 Flexbox 布局 */
            align-items: center; /* 默认垂直居中对齐 */
            flex-wrap: wrap;     /* 允许内容换行 */
            gap: 10px;           /* 设置元素之间的默认间距 */
        }

        .query-form .form-group label {
            font-weight: bold;
            margin-right: 5px;  /* 标签和控件之间加一点间距 */
            flex-shrink: 0;     /* 防止标签被压缩 */
            min-width: 80px;   /* 给标签一个最小宽度，尝试对齐 */
            text-align: right; /* 标签右对齐 */
        }

        /* 查询条件特殊处理 */
        #query-conditions { /* 包裹所有条件行的容器 */
            width: 100%; /* 让条件容器占满父元素的宽度 */
            /* margin-left: auto; */ /* 移除这个，避免右移 */
        }
        .query-form .form-group > button[onclick="addCondition()"] {
            width: 90px !important;
            padding: 6px 10px !important;
            font-size: 14px !important;
            margin-top: 0 !important;
            margin-left: 10px !important;
            flex-basis: auto !important;
            order: unset !important;
            display: inline-block !important;
            vertical-align: middle;
        }
        .condition-row {
            display: flex;       
            align-items: center; 
            gap: 8px;            
            flex-wrap: nowrap;
        }
        .condition-row button {
            margin-left: 0 !important;
        }
        .condition-row select, .condition-row input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .condition-row .field-select { width: 150px; }
        .condition-row .operator-select { width: 100px; }
        .condition-row .value-container { 
            flex: 1; 
            display: flex; 
            gap: 8px; 
        }
        .condition-row .value-input, .condition-row .value-input-end {
            flex: 1;
        }
        .condition-row button { /* 删除按钮 */
            padding: 4px 8px !important;
            font-size: 13px !important;
            margin-left: 6px !important;
            height: 32px !important;
            border-radius: 4px;
            cursor: pointer;
            border: none;
            background: #ff4d4f;
            color: white;
            flex-shrink: 0; /* 防止按钮被压缩 */
        }
        .date-shortcut-group button { /* 日期快捷按钮 */
             margin-right:4px; 
             padding:4px 10px; 
             border:1px solid #1677ff; 
             background:#e6f4ff; 
             color:#1677ff; 
             border-radius:4px; 
             cursor:pointer; 
             transition:all 0.2s;
        }
        .date-shortcut-group button:hover{
            background:#1677ff; 
            color:#fff;
        }

        /* --- 表单元素基础样式优化 --- */
        .query-form select,
        .query-form input[type="text"],
        .query-form input[type="number"],
        .query-form input[type="datetime-local"] {
            padding: 8px 10px; /* 统一内边距 */
            border: 1px solid #ccc; /* 稍微柔和的边框色 */
            border-radius: 4px;
            font-size: 14px; /* 统一字体大小 */
            font-family: inherit; /* 继承页面字体 */
            box-sizing: border-box; /* 确保padding和border包含在宽度内 */
            transition: border-color 0.2s, box-shadow 0.2s; /* 添加过渡效果 */
            vertical-align: middle; /* 尝试垂直对齐 */
        }
        /* 聚焦效果 */
        .query-form select:focus,
        .query-form input[type="text"]:focus,
        .query-form input[type="number"]:focus,
        .query-form input[type="datetime-local"]:focus {
            border-color: #1677ff; /* 边框变蓝 */
            outline: none; /* 移除默认的轮廓 */
            box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2); /* 添加蓝色光晕 */
        }
        
        /* 下拉框特殊微调 (可选) */
        .query-form select {
            /* 可以尝试添加背景图片来美化箭头，但跨浏览器兼容性较差 */
            /* appearance: none; */ /* 移除默认外观 */
            /* background: url('path/to/arrow.svg') no-repeat right 10px center; */
            /* background-size: 12px; */
        }
        
        /* 复选框和标签优化 */
        .query-form input[type="checkbox"] {
            margin-right: 6px; /* 复选框和文字间距加大 */
            vertical-align: middle;
            width: 15px; /* 可选：适当调整大小 */
            height: 15px;
        }
        #display-columns label { /* 包裹复选框和文字的标签 */
             vertical-align: middle;
             display: inline-flex; /* 改为inline-flex以便内部对齐 */
             align-items: center;
        }
        
        /* 调整其他控件的基础样式 */
        #query-table, #group-by-field, #query-limit {
            /* 移除之前的单独样式，让它们继承上面的通用样式 */
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        #query-table { width: 250px; } /* 可以适当加宽 */
        #group-by-field { width: 180px; }
        #query-limit { width: 100px; }
        
        /* 显示列区域 */
        #display-columns {
            margin-top: 0; /* 移除之前的上边距 */
            width: calc(100% - 90px); /* 尝试占满剩余宽度 */
            margin-left: 90px; /* 与标签宽度对齐 */
        }
        #display-columns > div { /* 内部的flex容器 */
            gap: 15px; /* 加大复选框之间的间距 */
        }

        /* 操作按钮区域 */
        .query-form .form-group:last-child { /* 最后一个form-group通常是按钮 */
             margin-top: 10px; /* 按钮区域和上面稍微拉开点距离 */
             margin-left: 90px; /* 与标签宽度对齐 */
        }
        .query-form .execute-btn, .query-form #export-btn {
            margin-top: 0; /* 移除之前的上边距 */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>数据库查询 - <?php echo htmlspecialchars($db_info['name']); ?></h2>
        </div>

        <div class="db-info">
            <p><strong>名称：</strong><?php echo htmlspecialchars($db_info['name']); ?></p>
            <p><strong>库名：</strong><?php echo htmlspecialchars($db_info['db_name']); ?></p>
            <p><strong>地址：</strong><?php echo htmlspecialchars(mask_middle($db_info['address'])); ?></p>
            <p><strong>帐号：</strong><?php echo htmlspecialchars(mask_middle($db_info['username'])); ?></p>
        </div>

        <div class="tabs">
            <div class="tab active" data-tab="sql">SQL查询</div>
            <div class="tab" data-tab="tables">数据表</div>
            <div class="tab" data-tab="query">数据查询</div>
        </div>

        <div id="sql-tab" class="tab-content active">
            <textarea class="sql-editor" placeholder="输入SQL语句..."></textarea>
            <button class="execute-btn" onclick="executeSQL()">执行</button>
            <div id="sql-result"></div>
        </div>

        <div id="tables-tab" class="tab-content">
            <h3>数据表列表</h3>
            <div id="tables-list" class="table-list">
                <div class="loading">加载中...</div>
            </div>
        </div>

        <div id="query-tab" class="tab-content">
            <div class="query-form">
                <div class="form-group">
                    <label>选择数据表：</label>
                    <select id="query-table" onchange="loadTableFields()" style="width:200px;padding:8px;border:1px solid #ddd;border-radius:4px;">
                        <option value="">请选择数据表</option>
                        <option value="factory_collection2_log" selected>2号采集日志</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>查询条件：<span style="color:#ff4d4f;font-size:14px;vertical-align:middle;">（查询天数不能大于35天）</span></label>
                    <div id="query-conditions">
                        <div class="condition-row" style="margin-bottom:10px;display:flex;align-items:center;gap:8px;">
                            <select class="field-select" style="width:150px;padding:8px;border:1px solid #ddd;border-radius:4px;">
                                <option value="">选择字段</option>
                                <option value="factory_no">工厂编号</option>
                                <option value="passage">产线编号</option>
                                <option value="num">采集数量</option>
                                <option value="ng_num">不良数量</option>
                                <option value="product_time" selected>生产时间</option>
                            </select>
                            <select class="operator-select" style="width:100px;padding:8px;border:1px solid #ddd;border-radius:4px;">
                                <option value="=">=</option>
                                <option value=">">></option>
                                <option value="<"><</option>
                                <option value=">=">>=</option>
                                <option value="<="><=</option>
                                <option value="like">包含</option>
                                <option value="not like">不包含</option>
                                <option value="between" selected>介于</option>
                                <option value="is not null">不为空</option>
                                <option value="is null">为空</option>
                            </select>
                            <div class="value-container" style="flex:1;display:flex;gap:8px;">
                                <input type="text" class="value-input" style="flex:1;padding:8px;border:1px solid #ddd;border-radius:4px;" placeholder="输入值">
                                <input type="text" class="value-input-end" style="flex:1;padding:8px;border:1px solid #ddd;border-radius:4px;display:none;" placeholder="结束值">
                            </div>
                            <button onclick="removeCondition(this)" style="background:#ff4d4f;color:white;border:none;padding:8px 12px;border-radius:4px;cursor:pointer;">删除</button>
                        </div>
                    </div>
                    <button onclick="addCondition()" style="background:#52c41a;color:white;border:none;padding:8px 16px;border-radius:4px;cursor:pointer;margin-top:10px;">添加条件</button>
                </div>
                <div class="form-group">
                    <label>汇总：</label>
                    <div id="query-group" style="display:flex;align-items:center;gap:8px;">
                        <select id="group-by-field" style="width:150px;padding:8px;border:1px solid #ddd;border-radius:4px;">
                            <option value="">选择汇总字段</option>
                            <!-- 可以在这里预置一个工厂编号选项，JS加载时会覆盖，但能提供初始默认 -->
                            <option value="factory_no" selected>工厂编号</option> 
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>显示列：</label>
                    <div id="display-columns" style="margin-top: 10px;">
                        <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="factory_no" checked> 工厂编号
                            </label>
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="passage" checked> 产线编号
                            </label>
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="num" checked> 采集数量
                            </label>
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="ng_num" checked> 不良数量
                            </label>
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="rate" checked> 采集率
                            </label>
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="num1" checked> 1#采集数量
                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label>显示条数：</label>
                    <input type="number" id="query-limit" value="100" min="1" max="1000" style="width:100px;padding:8px;border:1px solid #ddd;border-radius:4px;">
                </div>
                <button class="execute-btn" onclick="executeQuery()" style="margin-top:20px;">执行查询</button>
                <button class="execute-btn" id="append-query-btn" onclick="appendQuery()" style="margin-top:20px;margin-left:10px;background:#722ed1;display:none;">追加查询</button>
                <button class="execute-btn" id="export-btn" onclick="exportData()" style="margin-top:20px;margin-left:10px;background:#52c41a;">导出数据</button>
            </div>
            <div id="query-result" style="margin-top:20px;"></div>
        </div>
    </div>

    <a href="index.php" class="float-back-btn">返回首页</a>
    <button class="back-to-top" title="返回顶部">↑</button>

    <!-- Toast提示框 -->
    <div id="toast" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;min-width:180px;padding:18px 32px;background:rgba(0,0,0,0.85);color:#fff;border-radius:8px;font-size:18px;box-shadow:0 2px 12px rgba(0,0,0,0.18);text-align:center;pointer-events:none;transition:all 0.3s;"></div>

    <script>
        // 加载字典数据
        let dictionary = <?php echo json_encode($dictionary); ?>;
        
        // 转换表名为中文
        function translateTableName(tableName) {
            return dictionary.tables?.[tableName] || tableName;
        }
        
        // 转换字段名为中文
        function translateFieldName(fieldName) {
            return dictionary.fields?.[fieldName] || fieldName;
        }

        // scrollToTop 函数定义
        function scrollToTop() {
            console.log('scrollToTop function called.'); // 保留调试日志
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        }
        // 函数定义结束

        // 初始化标签切换功能
        function initTabs() {
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => {
                tab.onclick = function() {
                    const tabName = this.getAttribute('data-tab');
                    if (tabName) {
                        // 移除所有标签的active类
                        document.querySelectorAll('.tab').forEach(t => {
                            t.classList.remove('active');
                        });
                        
                        // 移除所有内容的active类
                        document.querySelectorAll('.tab-content').forEach(content => {
                            content.classList.remove('active');
                        });
                        
                        // 为当前标签添加active类
                        this.classList.add('active');
                        
                        // 显示对应的内容
                        const content = document.getElementById(`${tabName}-tab`);
                        if (content) {
                            content.classList.add('active');
                        }
                        
                        // 如果切换到数据表标签，加载数据表列表
                        if (tabName === 'tables') {
                            loadTables();
                        }
                    }
                };
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM Content Loaded');
            // 初始化标签切换
            initTabs();
            
            // 如果当前是数据表标签，加载数据表列表
            const activeTab = document.querySelector('.tab.active');
            if (activeTab && activeTab.getAttribute('data-tab') === 'tables') {
                loadTables();
            }
            
            // 从字典中获取数据表选项
            const tableSelect = document.getElementById('query-table');
            if (tableSelect) {
                let options = '<option value="">请选择数据表</option>';
                if (dictionary.tables) {
                    for (const [tableName, displayName] of Object.entries(dictionary.tables)) {
                        options += `<option value="${tableName}">${displayName}</option>`;
                    }
                }
                tableSelect.innerHTML = options;
            }

            // 监听滚动事件
            window.addEventListener('scroll', function() {
                const backToTop = document.querySelector('.back-to-top');
                if (backToTop) {
                    if (window.scrollY > 300) {
                        backToTop.classList.add('visible');
                    } else {
                        backToTop.classList.remove('visible');
                    }
                }
            });

            // 为返回顶部按钮添加点击事件监听器
            const backToTopButton = document.querySelector('.back-to-top');
            if (backToTopButton) {
                backToTopButton.addEventListener('click', scrollToTop);
            }

            // 初始化条件行的事件监听器
            bindConditionEventListeners();

            // 移除flatpickr初始化代码
            // ... 省略部分 ...
        });

        // 加载数据表列表
        function loadTables() {
            const tablesList = document.getElementById('tables-list');
            tablesList.innerHTML = '<div class="loading">加载中...</div>';
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');
            if (!dbId) {
                tablesList.innerHTML = '<div class="error-message">数据库ID不存在</div>';
                return;
            }
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=get_tables&id=${dbId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.tables.length === 0) {
                        tablesList.innerHTML = '<div class="loading">暂无数据表</div>';
                        return;
                    }
                    let html = '';
                    data.tables.forEach(table => {
                        // Use the original table name for copying
                        const originalTableName = table.name;
                        const displayName = translateTableName(originalTableName);
                        html += `
                            <div class="table-item" ondblclick="showTableDetail('${originalTableName}', this)">
                                <div class="table-header">
                                    <span class="table-name" onclick="copyTableName('${originalTableName}', this)" title="单击复制表名: ${originalTableName}">${displayName}</span>
                                    <span class="table-original-name" onclick="copyTableName('${originalTableName}', this)" title="单击复制表名: ${originalTableName}" style="color:#999;font-size:12px;margin-left:8px;">(${originalTableName})</span>
                                </div>
                                <div class="table-detail"></div>
                            </div>
                        `;
                    });
                    tablesList.innerHTML = html;
                } else {
                    tablesList.innerHTML = `<div class="error-message">${data.message}</div>`;
                }
            })
            .catch(error => {
                tablesList.innerHTML = `<div class="error-message">加载失败：${error.message}</div>`;
            });
        }

        // 复制表名
        function copyTableName(tableName, element) {
            navigator.clipboard.writeText(tableName).then(() => {
                showToast(`表名 "${tableName}" 已复制`, 'success');
                // 可选：添加一个短暂的视觉反馈，例如更改元素背景色
                const originalColor = element.style.backgroundColor;
                element.style.backgroundColor = '#e6f4ff'; 
                setTimeout(() => {
                   element.style.backgroundColor = originalColor;
                }, 500);
            }).catch(err => {
                showToast('复制失败: ' + err, 'error');
            });
            // 阻止事件冒泡到 ondblclick
            event.stopPropagation(); 
        }

        // 新增：复制列名到剪贴板
        function copyColumnName(columnName, element) {
            navigator.clipboard.writeText(columnName).then(() => {
                showToast(`列名 "${columnName}" 已复制`, 'success');
                // 可选：添加一个短暂的视觉反馈
                const originalColor = element.style.backgroundColor;
                element.style.backgroundColor = '#e6f4ff'; 
                setTimeout(() => {
                   element.style.backgroundColor = originalColor;
                }, 500);
            }).catch(err => {
                showToast('复制失败: ' + err, 'error');
            });
            event.stopPropagation(); 
        }

        // 显示表详情
        function showTableDetail(tableName, el) {
            const detailDiv = el.querySelector('.table-detail');
            // 如果当前表已展开，则收起并取消高亮，直接返回
            if (detailDiv.style.display === 'block') {
                detailDiv.style.display = 'none';
                detailDiv.innerHTML = '';
                el.classList.remove('active');
                return;
            }
            // 否则，先收起所有表，再展开当前表
            document.querySelectorAll('.table-detail').forEach(div => {
                div.style.display = 'none';
                div.innerHTML = '';
            });
            document.querySelectorAll('.table-item').forEach(item => {
                item.classList.remove('active');
            });
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');
            detailDiv.innerHTML = '加载中...';
            detailDiv.style.display = 'block';
            el.classList.add('active');
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=get_table_detail&id=${dbId}&table=${encodeURIComponent(tableName)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    let html = `<div class='table-count'>记录数：${data.count}</div>`;
                    html += '<table class="result-table"><tr>';
                    data.columns.forEach(col => {
                        const originalFieldName = col.Field; // Store original field name
                        const displayName = translateFieldName(originalFieldName);
                        html += `<th onclick="copyColumnName('${originalFieldName}', this)" title="单击复制列名: ${originalFieldName}" style="cursor:pointer;">${displayName}<br><span style="color:#999;font-size:10px;">(${originalFieldName})</span></th>`;
                    });
                    html += '</tr>';
                    data.data.forEach(row => {
                        html += '<tr>';
                        data.columns.forEach(col => {
                            html += `<td>${row[col.Field] ?? ''}</td>`;
                        });
                        html += '</tr>';
                    });
                    html += '</table>';
                    detailDiv.innerHTML = html;
                } else {
                    detailDiv.innerHTML = `<div class=\"error-message\">${data.message}</div>`;
                }
            })
            .catch(error => {
                detailDiv.innerHTML = `<div class=\"error-message\">加载失败：${error.message}</div>`;
            });
        }

        // 执行SQL
        function executeSQL() {
            const sql = document.querySelector('.sql-editor').value;
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');
            if (!sql.trim()) {
                showToast('请输入SQL语句', 'error');
                return;
            }
            const resultDiv = document.getElementById('sql-result');
            resultDiv.innerHTML = '执行中...';
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=exec_sql&id=${dbId}&sql=${encodeURIComponent(sql)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.data.length === 0) {
                        resultDiv.innerHTML = '<div class="loading">无数据</div>';
                        return;
                    }

                    // 生成表格
                    let html = '<table class="result-table">';
                    
                    // 添加查询条件说明
                    let conditionText = [];
                    document.querySelectorAll('.condition-row').forEach(row => {
                        const field = row.querySelector('.field-select').value;
                        const operator = row.querySelector('.operator-select').value;
                        const value = row.querySelector('.value-input').value;
                        const valueEnd = row.querySelector('.value-input-end').value;
                        
                        if (field && operator) {
                            let condition = translateFieldName(field);
                            if (operator === 'between' && value && valueEnd) {
                                const startDate = new Date(value);
                                const endDate = new Date(valueEnd);
                                const formatDate = (date) => {
                                    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                };
                                condition += ` 介于 ${formatDate(startDate)} 至 ${formatDate(endDate)}`;
                            } else if (operator === 'is null') {
                                condition += ' 为空';
                            } else if (operator === 'is not null') {
                                condition += ' 不为空';
                            } else if (value) {
                                if (field === 'product_time') {
                                    const date = new Date(value);
                                    const formatDate = (date) => {
                                        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                    };
                                    condition += ` ${operator} ${formatDate(date)}`;
                                } else {
                                    condition += ` ${operator} ${value}`;
                                }
                            }
                            conditionText.push(condition);
                        }
                    });

                    // 添加汇总说明
                    const groupByField = document.getElementById('group-by-field').value;
                    if (groupByField) {
                        conditionText.push(`按 ${translateFieldName(groupByField)} 汇总`);
                    }

                    // 添加条件说明行
                    if (conditionText.length > 0) {
                        html += '<tr><td colspan="' + (groupByField ? 4 : selectedColumns.length) + '" style="background-color: #f5f5f5; padding: 8px; font-weight: bold;">';
                        html += '查询条件：' + conditionText.join('，');
                        html += '</td></tr>';
                    }
                    
                    // 根据是否有汇总字段来决定表头
                    if (groupByField) {
                        html += '<tr>';
                        html += `<th>${translateFieldName(groupByField)}</th>`;
                        if (selectedColumns.includes('num')) {
                            html += '<th style="text-align: right;">采集数量</th>';
                        }
                        if (selectedColumns.includes('ng_num')) {
                            html += '<th style="text-align: right;">不良数量</th>';
                        }
                        if (selectedColumns.includes('rate')) {
                            html += '<th style="text-align: right;">采集率</th>';
                        }
                        html += '</tr>';

                        // 计算总计
                        let totalNum = 0;
                        let totalNgNum = 0;
                        data.data.forEach(row => {
                            if (selectedColumns.includes('num')) {
                                totalNum += parseInt(row.total_num) || 0;
                            }
                            if (selectedColumns.includes('ng_num')) {
                                totalNgNum += parseInt(row.total_ng_num) || 0;
                            }
                        });

                        // 输出汇总数据
                        data.data.forEach(row => {
                            html += '<tr>';
                            const fieldValue = dictionary.factory_codes && groupByField === 'factory_no' 
                                ? dictionary.factory_codes[row[groupByField]] 
                                : row[groupByField];
                            html += `<td>${fieldValue || ''}</td>`;
                            if (selectedColumns.includes('num')) {
                                html += `<td style="text-align: right;">${row.total_num || 0}</td>`;
                            }
                            if (selectedColumns.includes('ng_num')) {
                                html += `<td style="text-align: right;">${row.total_ng_num || 0}</td>`;
                            }
                            if (selectedColumns.includes('rate')) {
                                html += `<td style="text-align: right;" class="rate-cell">${row.rate || '0.00'}%</td>`;
                                factoryRates.push(rateValue);
                                allRates.push(rateValue);
                            }
                            html += '</tr>';
                        });

                        // 输出总计行
                        const totalRate = totalNum > 0 ? ((1 - totalNgNum / totalNum) * 100).toFixed(2) : '0.00';
                        html += '<tr class="factory-summary" style="font-weight:bold; background-color: #d6e4ff !important;">';
                        html += '<td>总计</td>';
                        if (selectedColumns.includes('num')) {
                            html += `<td style="text-align: right;">${totalNum}</td>`;
                        }
                        if (selectedColumns.includes('ng_num')) {
                            html += `<td style="text-align: right;">${totalNgNum}</td>`;
                        }
                        if (selectedColumns.includes('rate')) {
                            html += `<td style="text-align: right;" class="rate-cell">${totalRate}%</td>`;
                        }
                        html += '</tr>';
                    } else {
                        // 非汇总显示逻辑
                        html += '<tr>';
                        selectedColumns.forEach(col => {
                            html += `<th>${translateFieldName(col)}</th>`;
                        });
                        html += '</tr>';

                        data.data.forEach(row => {
                            html += '<tr>';
                            selectedColumns.forEach(col => {
                                let value = row[col];
                                if (col === 'factory_no' && dictionary.factory_codes) {
                                    value = dictionary.factory_codes[value] || value;
                                }
                                if (col === 'num' || col === 'ng_num') {
                                    html += `<td style="text-align: right;">${value || 0}</td>`;
                                } else if (col === 'rate') {
                                    html += `<td style="text-align: right;" class="rate-cell">${value || '0.00'}%</td>`;
                                } else {
                                    html += `<td>${value || ''}</td>`;
                                }
                            });
                            html += '</tr>';
                        });
                    }

                    html += '</table>';
                    resultDiv.innerHTML = html;
                    showToast('查询完成', 'success');

                    // *** 新增：添加JS悬停效果 ***
                    const tableBody = resultDiv.querySelector('.result-table tbody');
                    if (tableBody) {
                        const rows = tableBody.querySelectorAll('tr');
                        rows.forEach(row => {
                            // Store the computed original background color in a data attribute
                            row.dataset.originalBg = window.getComputedStyle(row).backgroundColor;
                            
                            row.addEventListener('mouseover', () => {
                                // Retrieve the stored original background if needed (though not strictly necessary for setting hover)
                                // const originalBg = row.dataset.originalBg;
                                
                                // Set hover background
                                if (row.classList.contains('factory-summary')) {
                                    row.style.backgroundColor = '#cce5ff'; // Darker blue for summary
                                } else {
                                    row.style.backgroundColor = '#e6f4ff'; // Lighter blue for normal
                                }
                                row.style.cursor = 'pointer';
                            });
                            
                            row.addEventListener('mouseout', () => {
                                // Restore the original background from the data attribute
                                row.style.backgroundColor = row.dataset.originalBg || ''; // Use stored or default
                                row.style.cursor = 'default';
                            });
                        });
                    }
                    // *** 结束：添加JS悬停效果 ***

                } else {
                    console.error('Query error:', data.message);
                    resultDiv.innerHTML = `<div class="error-message">${data.message}</div>`;
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Query execution error:', error);
                resultDiv.innerHTML = `<div class="error-message">执行失败：${error.message}</div>`;
                showToast('查询执行失败：' + error.message, 'error');
            });
        }

        // 加载表字段
        function loadTableFields() {
            const tableSelect = document.getElementById('query-table');
            const tableName = tableSelect.value;
            if (!tableName) {
                // 清空字段选择器
                document.querySelectorAll('.field-select').forEach(select => {
                    select.innerHTML = '<option value="">选择字段</option>';
                });
                document.getElementById('order-field').innerHTML = '<option value="">选择字段</option>';
                document.getElementById('group-by-field').innerHTML = '<option value="">选择汇总字段</option>';
                return;
            }

            // 从数据库获取表结构
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');
            
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=get_table_detail&id=${dbId}&table=${encodeURIComponent(tableName)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 构建字段选项，只包含字典中维护的字段，并强制包含生产时间
                    let fieldOptions = '';
                    let productTimeExists = false;
                    if (dictionary.fields) {
                        for (const [fieldKey, fieldName] of Object.entries(dictionary.fields)) {
                            if (data.columns.some(col => col.Field === fieldKey)) {
                                fieldOptions += `<option value="${fieldKey}">${fieldName}</option>`;
                                if (fieldKey === 'product_time') {
                                    productTimeExists = true;
                                }
                            }
                        }
                    }
                    // 如果字典或实际字段中没有生产时间，手动添加
                    if (!productTimeExists) {
                        fieldOptions += `<option value="product_time">生产时间</option>`;
                    }
                    
                    // 更新所有字段选择器（保留第一个"选择字段"选项）
                    const firstOption = '<option value="">选择字段</option>';
                    document.querySelectorAll('.field-select').forEach(select => {
                        const currentValue = select.value; // 保留当前选中的值
                        select.innerHTML = firstOption + fieldOptions;
                        // 尝试恢复之前的选中值，如果存在
                        if (select.querySelector(`option[value="${currentValue}"]`)) {
                            select.value = currentValue;
                        } else if (currentValue === 'product_time') { // 确保默认值能选上
                            select.value = 'product_time';
                        }
                    });
                    
                    // 更新汇总字段选择器...
                    const groupBySelect = document.getElementById('group-by-field');
                    const currentGroupByValue = groupBySelect.value; 
                    // groupBySelect.innerHTML = '<option value="">选择汇总字段</option>' + fieldOptions.substring(fieldOptions.indexOf('</option>') + 9); 
                    groupBySelect.innerHTML = '<option value="">选择汇总字段</option>' + fieldOptions; // 直接用完整选项
                    // ... (保持factory_no选中的逻辑不变) ...
                    if (groupBySelect.querySelector('option[value="factory_no"]')) {
                        groupBySelect.value = 'factory_no';
                    } else if (groupBySelect.querySelector(`option[value="${currentGroupByValue}"]`)) {
                        groupBySelect.value = currentGroupByValue;
                    } else {
                         groupBySelect.value = ''; 
                    }

                    // 更新显示列选择器...
                    const displayColumnsDiv = document.getElementById('display-columns');
                    let columnsHtml = '<div style="display: flex; flex-wrap: wrap; gap: 10px;">';
                    let hasRateCheckbox = false; // 标记是否已添加采集率复选框
                    if (dictionary.fields) {
                        for (const [fieldKey, fieldName] of Object.entries(dictionary.fields)) {
                            // 检查该字段是否存在于当前表中
                            if (data.columns.some(col => col.Field === fieldKey)) {
                                columnsHtml += `
                                    <label style="display: flex; align-items: center; gap: 4px;">
                                        <input type="checkbox" class="display-column" value="${fieldKey}" checked> ${fieldName}
                                    </label>`;
                                if (fieldKey === 'rate') {
                                    hasRateCheckbox = true;
                                }
                            }
                        }
                    }
                    // 确保采集率复选框总是存在（如果依赖字段存在）
                    const hasNum = data.columns.some(col => col.Field === 'num');
                    const hasNgNum = data.columns.some(col => col.Field === 'ng_num');
                    if (!hasRateCheckbox && hasNum && hasNgNum) { 
                        columnsHtml += `
                            <label style="display: flex; align-items: center; gap: 4px;">
                                <input type="checkbox" class="display-column" value="rate" checked> ${translateFieldName('rate')}
                            </label>`;
                    }
                    // 添加1#采集数量选项
                    columnsHtml += `
                        <label style="display: flex; align-items: center; gap: 4px;">
                            <input type="checkbox" class="display-column" value="num1" checked> 1#采集数量
                        </label>`;
                    columnsHtml += '</div>';
                    displayColumnsDiv.innerHTML = columnsHtml;

                    // 重新绑定事件监听器
                    bindConditionEventListeners();

                    // 添加显示列变化事件监听
                    document.querySelectorAll('.display-column').forEach(checkbox => {
                        checkbox.addEventListener('change', function() {
                            const checkedColumns = document.querySelectorAll('.display-column:checked');
                            if (checkedColumns.length === 0) {
                                this.checked = true; // 至少保持一个选中
                                showToast('至少需要选择一列显示', 'error');
                            }
                        });
                    });
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                showToast('加载字段失败：' + error.message, 'error');
            });
        }

        // 绑定条件事件监听器
        function bindConditionEventListeners() {
            document.querySelectorAll('#query-conditions .condition-row').forEach(row => {
                const fieldSelect = row.querySelector('.field-select');
                const operatorSelect = row.querySelector('.operator-select');

                // 为字段选择器添加change事件
                fieldSelect.onchange = function() {
                    updateValueInputs(this);
                };
                
                // 为操作符选择器添加change事件
                operatorSelect.onchange = function() {
                    updateValueInputs(this);
                };
                
                // 初始化时调用一次以设置正确的输入框
                updateValueInputs(fieldSelect);
            });
        }
        
        // 更新条件输入框
        function updateValueInputs(element) {
            const row = element.closest('.condition-row');
            const fieldSelect = row.querySelector('.field-select');
            const operatorSelect = row.querySelector('.operator-select');
            const valueInput = row.querySelector('.value-input');
            const valueInputEnd = row.querySelector('.value-input-end');
            const deleteBtn = row.querySelector('button');
            const selectedField = fieldSelect.value;
            const selectedOperator = operatorSelect.value;
        
            // 先重置
            valueInputEnd.style.display = 'none';
            valueInput.type = 'text';
            valueInputEnd.type = 'text';
            valueInput.className = 'value-input';
            valueInputEnd.className = 'value-input-end';
            valueInput.placeholder = '输入值';
            valueInputEnd.placeholder = '结束值';
            valueInput.step = 'any'; // 重置步长
            valueInputEnd.step = 'any';
        
            // 移除可能存在的日期快捷按钮组
            row.querySelectorAll('.date-shortcut-group').forEach(function(group) {
                group.remove();
            });
        
            if (selectedField) {
                // 根据字段类型设置输入框类型
                if (selectedField === 'product_time') {
                    valueInput.type = 'datetime-local';
                    valueInputEnd.type = 'datetime-local';
                    valueInput.className = 'value-input datetime-input';
                    valueInputEnd.className = 'value-input-end datetime-input';
                    valueInput.placeholder = '开始日期时间';
                    valueInputEnd.placeholder = '结束日期时间';
                    valueInput.step = '1'; // 秒
                    valueInputEnd.step = '1';
                } else if (selectedField === 'num' || selectedField === 'ng_num') {
                    valueInput.type = 'number';
                    valueInputEnd.type = 'number';
                    valueInput.placeholder = '数值';
                    valueInputEnd.placeholder = '结束数值';
                }
        
                // 根据操作符显示/隐藏结束值输入框
                if (selectedOperator === 'between') {
                    valueInputEnd.style.display = 'inline-block';
                    valueInput.placeholder = '开始值';
                    // 如果是生产时间且操作符是between，添加快捷按钮
                    if (selectedField === 'product_time') {
                        // 1. 移除已有的快捷按钮组
                        row.querySelectorAll('.date-shortcut-group').forEach(function(group) {
                            group.remove();
                        });
                        // 2. 移除已有的"上个月"按钮（只移除这个，保留上周）
                        row.querySelectorAll('.shortcut-btn[onclick*="setLastMonth"]').forEach(function(btn) {
                            btn.remove();
                        });
                        // 3. 插入新的快捷按钮组
                        let btnHtml = `<div class="date-shortcut-group" style="display:inline-block;margin-left:8px;">
                            <button type="button" class="shortcut-btn" onclick="setLastMonth(this)">上个月</button>
                            <button type="button" class="shortcut-btn" onclick="setLastWeek(this)">上周</button>
                        </div>`;
                        valueInputEnd.parentNode.insertBefore(document.createRange().createContextualFragment(btnHtml), valueInputEnd.nextSibling);
                        // 4. 再把删除按钮移动到快捷按钮组后面
                        const btnGroupNode = row.querySelector('.date-shortcut-group');
                        if (btnGroupNode && deleteBtn) {
                            btnGroupNode.parentNode.insertBefore(deleteBtn, btnGroupNode.nextSibling);
                        }
                    }
                } else if (selectedOperator === 'is null' || selectedOperator === 'is not null') {
                    valueInput.style.display = 'none';
                    valueInputEnd.style.display = 'none';
                } else {
                    valueInput.style.display = 'inline-block';
                }
            }
        }
        
        // 快捷按钮函数
        window.setLastMonth = function(btn) {
            const row = btn.closest('.condition-row');
            const valueInput = row.querySelector('.value-input');
            const valueInputEnd = row.querySelector('.value-input-end');
            const now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth(); // 上个月是 getMonth()
            if (month === 0) { // 如果当前是1月 (getMonth() 返回 0)
                year -= 1;
                month = 11; // 上个月是去年的12月 (getMonth() 返回 11)
            } else {
                month -= 1; // 其他月份直接减1
            }
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0); // 获取上个月的最后一天
            
            // 格式化日期时间，确保包含时分秒
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            
            // 设置开始日期（月初 00:00:00）
            const start = `${formatDate(firstDay)}T00:00:00`;
            // 设置结束日期（月末 23:59:59）
            const end = `${formatDate(lastDay)}T23:59:59`;
            
            console.log('Setting last month dates:', { start, end });
            
            valueInput.value = start;
            valueInputEnd.value = end;
            
            // 触发change事件以确保值更新
            valueInput.dispatchEvent(new Event('change'));
            valueInputEnd.dispatchEvent(new Event('change'));
        };

        window.setLastWeek = function(btn) {
            const row = btn.closest('.condition-row');
            const valueInput = row.querySelector('.value-input');
            const valueInputEnd = row.querySelector('.value-input-end');
            const now = new Date();
            const today = now.getDay(); // 0 (周日) - 6 (周六)
            const diffToMonday = today === 0 ? -6 : 1 - today; // 计算到本周一的偏移量
            const lastMonday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diffToMonday - 7);
            const lastSunday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diffToMonday - 1);
            
            // 格式化日期时间，确保包含时分秒
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            
            // 设置开始日期（周一 00:00:00）
            const start = `${formatDate(lastMonday)}T00:00:00`;
            // 设置结束日期（周日 23:59:59）
            const end = `${formatDate(lastSunday)}T23:59:59`;
            
            console.log('Setting last week dates:', { start, end });
            
            valueInput.value = start;
            valueInputEnd.value = end;
            
            // 触发change事件以确保值更新
            valueInput.dispatchEvent(new Event('change'));
            valueInputEnd.dispatchEvent(new Event('change'));
        };

        // 添加条件
        function addCondition() {
            const conditionsDiv = document.getElementById('query-conditions');
            const firstRow = conditionsDiv.querySelector('.condition-row');
            const newRow = firstRow.cloneNode(true);
            // 重置新行的输入值
            newRow.querySelector('.value-input').value = '';
            newRow.querySelector('.value-input-end').value = '';
            // 移除可能克隆过来的快捷按钮组
            let btnGroup = newRow.querySelector('.date-shortcut-group');
            if (btnGroup) btnGroup.remove();
            
            // 为新行的下拉框重新绑定事件监听器
            const newFieldSelect = newRow.querySelector('.field-select');
            const newOperatorSelect = newRow.querySelector('.operator-select');
            newFieldSelect.onchange = function() {
                updateValueInputs(this);
            };
            newOperatorSelect.onchange = function() {
                updateValueInputs(this);
            };
            
            // 触发一次更新以确保初始状态正确
            updateValueInputs(newFieldSelect);
            
            conditionsDiv.appendChild(newRow);
        }

        // 移除条件
        function removeCondition(button) {
            const conditionsDiv = document.getElementById('query-conditions');
            if (conditionsDiv.children.length > 1) {
                button.closest('.condition-row').remove();
            }
        }

        // 添加全局变量存储第一次查询的结果
        let firstQueryResult = null;
        let firstQueryTable = null;

        // 修改执行查询函数
        function executeQuery() {
            const tableName = document.getElementById('query-table').value;
            if (!tableName) {
                showToast('请选择数据表', 'error');
                return;
            }

            // 检查是否已经执行过查询
            if (firstQueryResult) {
                showToast('请更换数据表进行追加查询', 'error');
                return;
            }

            // 重置追加查询相关状态
            firstQueryResult = null;
            firstQueryTable = null;
            document.getElementById('append-query-btn').style.display = 'none';

            // 获取选中的显示列
            const selectedColumns = Array.from(document.querySelectorAll('.display-column:checked')).map(cb => cb.value);
            console.log('Selected columns array:', selectedColumns);
            if (selectedColumns.length === 0) {
                showToast('请至少选择一列显示', 'error');
                return;
            }

            // 构建查询条件
            const conditions = [];
            let hasError = false;
            document.querySelectorAll('.condition-row').forEach(row => {
                if (hasError) return;
                
                const field = row.querySelector('.field-select').value;
                const operator = row.querySelector('.operator-select').value;
                const value = row.querySelector('.value-input').value;
                const valueEnd = row.querySelector('.value-input-end').value;
                
                if (field && operator) {
                    if (operator === 'between' && field === 'product_time') {
                        if (!value || !valueEnd) {
                            showToast('请完整填写开始和结束日期时间', 'error');
                            hasError = true;
                            return;
                        }
                        
                        const startDate = formatDateTime(value);
                        const endDate = formatDateTime(valueEnd);
                        
                        if (!startDate || !endDate) {
                            showToast('日期格式无效，请使用正确的日期时间格式', 'error');
                            hasError = true;
                            return;
                        }
                        
                        conditions.push(`t.${field} BETWEEN '${startDate}' AND '${endDate}'`);
                    } else if (operator === 'is null') {
                        conditions.push(`t.${field} IS NULL`);
                    } else if (operator === 'is not null') {
                        conditions.push(`t.${field} IS NOT NULL`);
                    } else if (value) {
                        if (field === 'product_time') {
                            const formattedValue = formatDateTime(value);
                            if (!formattedValue) {
                                showToast('日期格式无效，请使用正确的日期时间格式', 'error');
                                hasError = true;
                                return;
                            }
                            conditions.push(`t.${field} ${operator} '${formattedValue}'`);
                        } else {
                            conditions.push(`t.${field} ${operator} '${value}'`);
                        }
                    }
                }
            });

            if (hasError) return;

            if (conditions.length === 0) {
                showToast('请至少输入一个有效的查询条件', 'error');
                return;
            }

            // 获取汇总字段
            const groupByField = document.getElementById('group-by-field').value;
            
            // 构建查询语句
            let query = '';
            if (groupByField) {
                if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                    const selectFields = [
                        't.factory_no',
                        't.passage',
                        ...(selectedColumns.includes('num') ? ['SUM(t.num) as total_num'] : []),
                        ...(selectedColumns.includes('ng_num') ? ['SUM(t.ng_num) as total_ng_num'] : []),
                        ...(selectedColumns.includes('rate') ? ['ROUND((1 - SUM(t.ng_num) / SUM(t.num)) * 100, 2) as rate'] : [])
                    ].filter(Boolean);
                    
                    if (!selectFields.includes('t.factory_no')) selectFields.unshift('t.factory_no');
                    if (!selectFields.includes('t.passage')) selectFields.splice(1, 0, 't.passage');
                    
                    query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                    if (conditions.length > 0) {
                        query += ` WHERE ${conditions.join(' AND ')}`;
                    }
                    query += ` GROUP BY t.factory_no, t.passage`;
                } else if (groupByField) {
                    const selectFields = [
                        `t.${groupByField}`,
                        ...(selectedColumns.includes('num') ? ['SUM(t.num) as total_num'] : []),
                        ...(selectedColumns.includes('ng_num') ? ['SUM(t.ng_num) as total_ng_num'] : []),
                        ...(selectedColumns.includes('rate') ? ['ROUND((1 - SUM(t.ng_num) / SUM(t.num)) * 100, 2) as rate'] : [])
                    ].filter(Boolean);
    
                    query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                    if (conditions.length > 0) {
                        query += ` WHERE ${conditions.join(' AND ')}`;
                    }
                    query += ` GROUP BY t.${groupByField}`;
                } else {
                    const selectFields = [];
                    if (selectedColumns.includes('factory_no')) {
                        selectFields.push('t.factory_no');
                    }
                    if (selectedColumns.includes('passage')) {
                        selectFields.push('t.passage');
                    }
                    if (selectedColumns.includes('num')) {
                        selectFields.push('t.num');
                    }
                    if (selectedColumns.includes('ng_num')) {
                        selectFields.push('t.ng_num');
                    }
                    if (selectedColumns.includes('rate')) {
                        selectFields.push('ROUND((1 - t.ng_num / t.num) * 100, 2) as rate');
                    }

                    if (selectFields.length === 0) {
                        showToast('请至少选择一列显示', 'error');
                        return;
                    }

                    query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                    if (conditions.length > 0) {
                        query += ` WHERE ${conditions.join(' AND ')}`;
                    }
                }
            } else {
                const selectFields = [];
                if (selectedColumns.includes('factory_no')) {
                    selectFields.push('t.factory_no');
                }
                if (selectedColumns.includes('passage')) {
                    selectFields.push('t.passage');
                }
                if (selectedColumns.includes('num')) {
                    selectFields.push('t.num');
                }
                if (selectedColumns.includes('ng_num')) {
                    selectFields.push('t.ng_num');
                }
                if (selectedColumns.includes('rate')) {
                    selectFields.push('ROUND((1 - t.ng_num / t.num) * 100, 2) as rate');
                }

                if (selectFields.length === 0) {
                    showToast('请至少选择一列显示', 'error');
                    return;
                }

                query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                if (conditions.length > 0) {
                    query += ` WHERE ${conditions.join(' AND ')}`;
                }
            }

            // 添加调试日志
            console.log('Final SQL Query:', query);
            console.log('Query conditions:', conditions);
            console.log('Selected columns:', selectedColumns);
            console.log('Group by field:', groupByField);

            // 执行查询
            const resultDiv = document.getElementById('query-result');
            resultDiv.innerHTML = '执行中...';
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');
            
            // 显示执行中的提示，并保存Promise，不自动关闭
            const toastPromise = showToast('正在执行查询...', 'info', false);
            
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=exec_sql&id=${dbId}&sql=${encodeURIComponent(query)}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    if (data.data.length === 0) {
                        resultDiv.innerHTML = '<div class="loading">无数据</div>';
                        hideToast();
                        showToast('查询完成，无数据', 'info', true);
                        return;
                    }

                    // 生成表格
                    let html = ''; // 清空，后面重新构建
                    let theadHtml = '<thead>';
                    let tbodyHtml = '<tbody>';
                    
                    // 添加查询条件说明
                    let conditionText = [];
                    document.querySelectorAll('.condition-row').forEach(row => {
                        const field = row.querySelector('.field-select').value;
                        const operator = row.querySelector('.operator-select').value;
                        const value = row.querySelector('.value-input').value;
                        const valueEnd = row.querySelector('.value-input-end').value;
                        
                        if (field && operator) {
                            let condition = translateFieldName(field);
                            if (operator === 'between' && value && valueEnd) {
                                const startDate = new Date(value);
                                const endDate = new Date(valueEnd);
                                const formatDate = (date) => {
                                    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                };
                                condition += ` 介于 ${formatDate(startDate)} 至 ${formatDate(endDate)}`;
                            } else if (operator === 'is null') {
                                condition += ' 为空';
                            } else if (operator === 'is not null') {
                                condition += ' 不为空';
                            } else if (value) {
                                if (field === 'product_time') {
                                    const date = new Date(value);
                                    const formatDate = (date) => {
                                        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                    };
                                    condition += ` ${operator} ${formatDate(date)}`;
                                } else {
                                    condition += ` ${operator} ${value}`;
                                }
                            }
                            conditionText.push(condition);
                        }
                    });

                    if (groupByField) {
                        conditionText.push(`按 ${translateFieldName(groupByField)} 汇总`);
                    }

                    // 添加条件说明行到 a separate variable first
                    let conditionRowHtml = '';
                    if (conditionText.length > 0) {
                        let colspan = selectedColumns.length;
                        if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                            colspan = 2 + (selectedColumns.includes('num1') ? 1 : 0) + (selectedColumns.includes('num') ? 1 : 0) + (selectedColumns.includes('ng_num') ? 1 : 0) + (selectedColumns.includes('rate') ? 1 : 0);
                        } else if (groupByField) {
                            colspan = 1 + (selectedColumns.includes('num1') ? 1 : 0) + (selectedColumns.includes('num') ? 1 : 0) + (selectedColumns.includes('ng_num') ? 1 : 0) + (selectedColumns.includes('rate') ? 1 : 0);
                        }
                        conditionRowHtml = '<tr><td colspan="' + colspan + '" style="background-color: #f5f5f5; padding: 8px; font-weight: bold; text-align: left;">';
                        conditionRowHtml += '查询条件：' + conditionText.join('，');
                        conditionRowHtml += '</td></tr>';
                    }
                    
                    // --- 开始生成表头 (thead) ---
                    theadHtml += conditionRowHtml; // Add condition row first
                    theadHtml += '<tr>'; // Header row start
                    if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                        theadHtml += `<th>${translateFieldName('factory_no')}</th>`;
                        theadHtml += `<th>${translateFieldName('passage')}</th>`;
                        if (selectedColumns.includes('num1')) { theadHtml += '<th style="text-align: right;">1#采集数量</th>'; }
                        if (selectedColumns.includes('num')) { theadHtml += '<th style="text-align: right;">2#采集数量</th>'; }
                        if (selectedColumns.includes('ng_num')) { theadHtml += '<th style="text-align: right;">不良数量</th>'; }
                        if (selectedColumns.includes('rate')) { theadHtml += '<th style="text-align: right;">采集率</th>'; }
                    } else if (groupByField) {
                        theadHtml += `<th>${translateFieldName(groupByField)}</th>`;
                        if (selectedColumns.includes('num1')) { theadHtml += '<th style="text-align: right;">1#采集数量</th>'; }
                        if (selectedColumns.includes('num')) { theadHtml += '<th style="text-align: right;">2#采集数量</th>'; }
                        if (selectedColumns.includes('ng_num')) { theadHtml += '<th style="text-align: right;">不良数量</th>'; }
                        if (selectedColumns.includes('rate')) { theadHtml += '<th style="text-align: right;">采集率</th>'; }
                    } else {
                        selectedColumns.forEach(col => {
                            let alignStyle = (col === 'num' || col === 'ng_num' || col === 'rate' || col === 'num1') ? ' style="text-align: right;"' : '';
                            let displayName = col === 'num1' ? '1#采集数量' : 
                                           col === 'num' ? '2#采集数量' : 
                                           translateFieldName(col);
                            theadHtml += `<th${alignStyle}>${displayName}</th>`;
                        });
                    }
                    theadHtml += '</tr>'; // Header row end
                    theadHtml += '</thead>';
                    // --- 结束生成表头 ---
                    
                    // --- 开始生成表格主体 (tbody) ---
                    if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                        const factoryRowSpans = {};
                        data.data.forEach(row => { factoryRowSpans[row.factory_no] = (factoryRowSpans[row.factory_no] || 0) + 1; });
                        let previousFactoryNo = null, 
                            factorySumNum = 0, 
                            factorySumNgNum = 0, 
                            factoryRates = [], 
                            grandSumNum = 0, 
                            grandSumNgNum = 0, 
                            allRates = [],
                            factorySumNum1 = 0,
                            grandSumNum1 = 0;
                        data.data.sort((a, b) => { 
                            if (a.factory_no < b.factory_no) return -1; 
                            if (a.factory_no > b.factory_no) return 1; 
                            if (a.passage < b.passage) return -1; 
                            if (a.passage > b.passage) return 1; 
                            return 0; 
                        });
                        data.data.forEach((row, index) => {
                            const currentFactoryNo = row.factory_no;
                            const factoryChanged = previousFactoryNo !== null && currentFactoryNo !== previousFactoryNo;
                            if (factoryChanged) { 
                                tbodyHtml += createSubtotalRow(previousFactoryNo, factorySumNum, factorySumNgNum, factoryRates, selectedColumns, factorySumNum1); 
                                factorySumNum = 0; 
                                factorySumNgNum = 0; 
                                factoryRates = []; 
                                factorySumNum1 = 0;
                            }
                            tbodyHtml += '<tr>';
                            if (currentFactoryNo !== previousFactoryNo) { 
                                const factoryValue = dictionary.factory_codes ? dictionary.factory_codes[currentFactoryNo] || currentFactoryNo : currentFactoryNo; 
                                const rowspan = factoryRowSpans[currentFactoryNo] || 1; 
                                tbodyHtml += `<td rowspan="${rowspan}">${factoryValue || ''}</td>`; 
                            }
                            tbodyHtml += `<td>${row.passage || ''}</td>`;
                            if (selectedColumns.includes('num1')) { 
                                const num1 = parseInt(row.num1) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${num1}</td>`; 
                                factorySumNum1 += num1;
                                grandSumNum1 += num1;
                            }
                            if (selectedColumns.includes('num')) { 
                                const num = parseInt(row.total_num) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${num}</td>`; 
                                factorySumNum += num; 
                                grandSumNum += num; 
                            }
                            if (selectedColumns.includes('ng_num')) { 
                                const ngNum = parseInt(row.total_ng_num) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${ngNum}</td>`; 
                                factorySumNgNum += ngNum; 
                                grandSumNgNum += ngNum; 
                            }
                            if (selectedColumns.includes('rate')) { 
                                const rateValue = parseFloat(row.rate) || 0; 
                                tbodyHtml += `<td style="text-align: right;" class="rate-cell">${rateValue.toFixed(2)}%</td>`; 
                                factoryRates.push(rateValue); 
                                allRates.push(rateValue); 
                            }
                            tbodyHtml += '</tr>';
                            previousFactoryNo = currentFactoryNo;
                            if (index === data.data.length - 1) { 
                                tbodyHtml += createSubtotalRow(currentFactoryNo, factorySumNum, factorySumNgNum, factoryRates, selectedColumns, factorySumNum1); 
                            }
                        });
                        tbodyHtml += createGrandTotalRow(grandSumNum, grandSumNgNum, allRates, selectedColumns, grandSumNum1);
                    } else if (groupByField) {
                        let totalNum = 0, totalNgNum = 0, totalNum1 = 0;
                        data.data.forEach(row => {
                            tbodyHtml += '<tr>';
                            const fieldValue = dictionary.factory_codes && groupByField === 'factory_no' ? dictionary.factory_codes[row[groupByField]] : row[groupByField];
                            tbodyHtml += `<td>${fieldValue || ''}</td>`;
                            if (selectedColumns.includes('num1')) { 
                                const num1 = parseInt(row.num1) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${num1}</td>`; 
                                totalNum1 += num1;
                            }
                            if (selectedColumns.includes('num')) { 
                                const num = parseInt(row.total_num) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${num}</td>`; 
                                totalNum += num; 
                            }
                            if (selectedColumns.includes('ng_num')) { 
                                const ngNum = parseInt(row.total_ng_num) || 0; 
                                tbodyHtml += `<td style="text-align: right;">${ngNum}</td>`; 
                                totalNgNum += ngNum; 
                            }
                            if (selectedColumns.includes('rate')) { 
                                tbodyHtml += `<td style="text-align: right;" class="rate-cell">${row.rate || '0.00'}%</td>`; 
                            }
                            tbodyHtml += '</tr>';
                        });
                        const totalRate = totalNum > 0 ? ((1 - totalNgNum / totalNum) * 100).toFixed(2) : '0.00';
                        tbodyHtml += '<tr class="factory-summary" style="font-weight:bold; background-color: #d6e4ff !important;">';
                        tbodyHtml += '<td>总计</td>';
                        if (selectedColumns.includes('num1')) { tbodyHtml += `<td style="text-align: right;">${totalNum1}</td>`; }
                        if (selectedColumns.includes('num')) { tbodyHtml += `<td style="text-align: right;">${totalNum}</td>`; }
                        if (selectedColumns.includes('ng_num')) { tbodyHtml += `<td style="text-align: right;">${totalNgNum}</td>`; }
                        if (selectedColumns.includes('rate')) { tbodyHtml += `<td style="text-align: right;" class="rate-cell">${totalRate}%</td>`; }
                        tbodyHtml += '</tr>';
                    } else {
                        data.data.forEach((row, rowIndex) => {
                            tbodyHtml += '<tr>';
                            selectedColumns.forEach(col => {
                                let value = row[col];
                                let alignStyle = (col === 'num' || col === 'ng_num' || col === 'rate' || col === 'num1') ? ' style="text-align: right;"' : '';
                                let className = (col === 'rate') ? ' class="rate-cell"' : '';
                                if (col === 'factory_no' && dictionary.factory_codes) { value = dictionary.factory_codes[value] || value; }
                                if (col === 'num' || col === 'ng_num' || col === 'num1') { value = value || 0; }
                                if (col === 'rate') { value = value || '0.00'; value += '%'; }
                                tbodyHtml += `<td${alignStyle}${className}>${value || ''}</td>`;
                            });
                            tbodyHtml += '</tr>';
                        });
                    }
                    tbodyHtml += '</tbody>';
                    // --- 结束生成表格主体 ---
                    
                    // 组合最终的HTML
                    html = '<table class="result-table">';
                    html += theadHtml;
                    html += tbodyHtml;
                    html += '</table>';
                    resultDiv.innerHTML = html;
                    hideToast();
                    showToast('查询完成', 'success', true);

                    // *** 新增：添加JS悬停效果 ***
                    const tableBody = resultDiv.querySelector('.result-table tbody');
                    if (tableBody) {
                        const rows = tableBody.querySelectorAll('tr');
                        rows.forEach(row => {
                            row.dataset.originalBg = window.getComputedStyle(row).backgroundColor;
                            
                            row.addEventListener('mouseover', () => {
                                if (row.classList.contains('factory-summary')) {
                                    row.style.backgroundColor = '#cce5ff';
                                } else {
                                    row.style.backgroundColor = '#e6f4ff';
                                }
                                row.style.cursor = 'pointer';
                            });
                            
                            row.addEventListener('mouseout', () => {
                                row.style.backgroundColor = row.dataset.originalBg || '';
                                row.style.cursor = 'default';
                            });
                        });
                    }
                    // *** 结束：添加JS悬停效果 ***

                    // 保存第一次查询的结果
                    firstQueryResult = data.data;
                    firstQueryTable = tableName;
                    
                    // 显示追加查询按钮
                    document.getElementById('append-query-btn').style.display = 'inline-block';
                    
                    // 禁用执行查询按钮
                    const executeBtn = document.querySelector('button[onclick="executeQuery()"]');
                    if (executeBtn) {
                        executeBtn.disabled = true;
                        executeBtn.style.backgroundColor = '#ccc';
                        executeBtn.style.cursor = 'not-allowed';
                        executeBtn.title = '请使用追加查询按钮进行后续查询';
                    }

                } else {
                    console.error('Query error:', data.message);
                    resultDiv.innerHTML = `<div class="error-message">${data.message}</div>`;
                    hideToast();
                    showToast(data.message, 'error', true);
                }
            })
            .catch(error => {
                console.error('Query execution error:', error);
                resultDiv.innerHTML = `<div class="error-message">执行失败：${error.message}</div>`;
                hideToast();
                showToast('查询执行失败：' + error.message, 'error', true);
            });
        }

        // 添加Toast提示函数
        function showToast(message, type = 'info', autoHide = true) {
            const toast = document.getElementById('toast');
            if (!toast) return Promise.resolve();
            
            // 设置消息和样式
            toast.textContent = message;
            toast.style.display = 'block';
            
            // 根据类型设置不同的样式
            switch(type) {
                case 'error':
                    toast.style.background = 'rgba(255, 77, 79, 0.9)';
                    break;
                case 'success':
                    toast.style.background = 'rgba(82, 196, 26, 0.9)';
                    break;
                case 'info':
                default:
                    toast.style.background = 'rgba(0, 0, 0, 0.85)';
            }
            
            // 返回一个Promise，允许调用者控制何时关闭
            return new Promise((resolve) => {
                // 存储resolve函数，以便后续调用
                toast._resolve = resolve;
                
                // 如果需要自动隐藏，设置定时器
                if (autoHide) {
            setTimeout(() => {
                        hideToast();
            }, 3000);
                }
            });
        }

        // 关闭Toast提示
        function hideToast() {
            const toast = document.getElementById('toast');
            if (toast) {
                toast.style.display = 'none';
                if (toast._resolve) {
                    toast._resolve();
                    delete toast._resolve;
                }
            }
        }

        // 添加日期验证函数
        function isValidDate(dateString) {
            // 检查日期格式是否为 YYYY-MM-DD HH:mm:ss 或 YYYY-MM-DDTHH:mm:ss
            const regex = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}$/;
            if (!regex.test(dateString)) {
                console.log('Invalid date format:', dateString);
                return false;
            }
            
            // 尝试创建日期对象
            const date = new Date(dateString);
            if (!(date instanceof Date) || isNaN(date)) {
                console.log('Invalid date value:', dateString);
                return false;
            }
            
            return true;
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) {
                console.log('Empty date string');
                return null;
            }
            
            // 将 T 替换为空格
            let formatted = dateString.replace('T', ' ');
            
            // 确保日期时间格式正确
            const date = new Date(formatted);
            if (isNaN(date.getTime())) {
                console.log('Invalid date:', dateString);
                return null;
            }
            
            // 格式化为 YYYY-MM-DD HH:mm:ss
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // --- 新增：辅助函数，用于创建小计/总计行 ---
        function createSubtotalRow(factoryNo, sumNum, sumNgNum, ratesArray, selectedColumns, sumNum1) {
            console.log(`Subtotal for ${factoryNo}: sumNum=${sumNum}, sumNgNum=${sumNgNum}, sumNum1=${sumNum1}, rates=`, ratesArray);
            let html = '<tr class="factory-summary" style="font-weight:bold; background-color: #e6f4ff !important;">';
            html += '<td colspan="2">小计</td>';
            if (selectedColumns.includes('num1')) {
                html += `<td style="text-align: right;">${sumNum1}</td>`;
            }
            if (selectedColumns.includes('num')) {
                html += `<td style="text-align: right;">${sumNum}</td>`;
            }
            if (selectedColumns.includes('ng_num')) {
                html += `<td style="text-align: right;">${sumNgNum}</td>`;
            }
            if (selectedColumns.includes('rate')) {
                let avgRate = 0;
                if (ratesArray && ratesArray.length > 0) {
                    const sumOfRates = ratesArray.reduce((acc, rate) => acc + (parseFloat(rate) || 0), 0);
                    avgRate = (sumOfRates / ratesArray.length).toFixed(2);
                } else {
                    avgRate = '0.00';
                }
                html += `<td style="text-align: right;" class="rate-cell">${avgRate}%</td>`;
            }
            html += '</tr>';
            return html;
        }

        function createGrandTotalRow(sumNum, sumNgNum, ratesArray, selectedColumns, sumNum1) {
            console.log(`Grand Total: sumNum=${sumNum}, sumNgNum=${sumNgNum}, sumNum1=${sumNum1}, rates=`, ratesArray);
            let html = '<tr class="factory-summary" style="font-weight:bold; background-color: #d6e4ff !important;">';
            html += '<td colspan="2">总计</td>';
            if (selectedColumns.includes('num1')) {
                html += `<td style="text-align: right;">${sumNum1}</td>`;
            }
            if (selectedColumns.includes('num')) {
                html += `<td style="text-align: right;">${sumNum}</td>`;
            }
            if (selectedColumns.includes('ng_num')) {
                html += `<td style="text-align: right;">${sumNgNum}</td>`;
            }
            if (selectedColumns.includes('rate')) {
                let avgRate = 0;
                if (ratesArray && ratesArray.length > 0) {
                    const sumOfRates = ratesArray.reduce((acc, rate) => acc + (parseFloat(rate) || 0), 0);
                    avgRate = (sumOfRates / ratesArray.length).toFixed(2);
                } else {
                    avgRate = '0.00';
                }
                html += `<td style="text-align: right;" class="rate-cell">${avgRate}%</td>`;
            }
            html += '</tr>';
            return html;
        }
        // --- 结束辅助函数 ---

        // 升级导出数据函数，支持rowspan和colspan，彻底解决格式错乱问题
        function exportData() {
            const resultTable = document.querySelector('.result-table');
            if (!resultTable) {
                showToast('没有可导出的数据', 'error');
                return;
            }

            // 生成文件名
            const now = new Date();
            const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
            const fileName = `导出数据-${timestamp}.csv`;

            // 先计算最大列数
            let maxCols = 0;
            const allRows = resultTable.querySelectorAll('tr');
            allRows.forEach(row => {
                let colCount = 0;
                row.querySelectorAll('th,td').forEach(cell => {
                    const colspan = parseInt(cell.getAttribute('colspan') || '1', 10);
                    colCount += colspan;
                });
                if (colCount > maxCols) maxCols = colCount;
            });

            // 构建二维数组，处理rowspan和colspan
            let tableArr = [];
            let rowIndex = 0;
            allRows.forEach(row => {
                if (!tableArr[rowIndex]) tableArr[rowIndex] = [];
                let cells = row.querySelectorAll('th,td');
                let colIndex = 0;
                cells.forEach(cell => {
                    // 跳过被rowspan占据的位置
                    while (tableArr[rowIndex][colIndex] !== undefined) colIndex++;
                    let text = (cell.innerText || cell.textContent).replace(/\r?\n|\r/g, ' ').replace(/"/g, '""').trim();
                    const colspan = parseInt(cell.getAttribute('colspan') || '1', 10);
                    const rowspan = parseInt(cell.getAttribute('rowspan') || '1', 10);
                    for (let i = 0; i < rowspan; i++) {
                        for (let j = 0; j < colspan; j++) {
                            let r = rowIndex + i;
                            let c = colIndex + j;
                            if (!tableArr[r]) tableArr[r] = [];
                            tableArr[r][c] = (i === 0 && j === 0) ? `"${text}"` : '""';
                        }
                    }
                    colIndex += colspan;
                });
                rowIndex++;
            });

            // 补齐每行
            let csv = '';
            tableArr.forEach(row => {
                while (row.length < maxCols) row.push('""');
                csv += row.join(',') + '\r\n';
            });

            // 创建Blob并下载
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            showToast('导出成功', 'success', true);
        }

        // 添加追加查询函数
        function appendQuery() {
            if (!firstQueryResult) {
                showToast('请先执行第一次查询', 'error');
                return;
            }

            const tableName = document.getElementById('query-table').value;
            if (!tableName) {
                showToast('请选择数据表', 'error');
                return;
            }

            if (tableName === firstQueryTable) {
                showToast('请选择不同的数据表进行追加查询', 'error');
                return;
            }

            // 获取选中的显示列
            const selectedColumns = Array.from(document.querySelectorAll('.display-column:checked')).map(cb => cb.value);
            if (selectedColumns.length === 0) {
                showToast('请至少选择一列显示', 'error');
                return;
            }

            // 构建查询条件
            const conditions = [];
            let hasError = false;
            document.querySelectorAll('.condition-row').forEach(row => {
                if (hasError) return;
                
                const field = row.querySelector('.field-select').value;
                const operator = row.querySelector('.operator-select').value;
                const value = row.querySelector('.value-input').value;
                const valueEnd = row.querySelector('.value-input-end').value;
                
                if (field && operator) {
                    if (operator === 'between' && field === 'product_time') {
                        if (!value || !valueEnd) {
                            showToast('请完整填写开始和结束日期时间', 'error');
                            hasError = true;
                            return;
                        }
                        
                        const startDate = formatDateTime(value);
                        const endDate = formatDateTime(valueEnd);
                        
                        if (!startDate || !endDate) {
                            showToast('日期格式无效，请使用正确的日期时间格式', 'error');
                            hasError = true;
                            return;
                        }
                        
                        conditions.push(`t.${field} BETWEEN '${startDate}' AND '${endDate}'`);
                    } else if (operator === 'is null') {
                        conditions.push(`t.${field} IS NULL`);
                    } else if (operator === 'is not null') {
                        conditions.push(`t.${field} IS NOT NULL`);
                    } else if (value) {
                        if (field === 'product_time') {
                            const formattedValue = formatDateTime(value);
                            if (!formattedValue) {
                                showToast('日期格式无效，请使用正确的日期时间格式', 'error');
                                hasError = true;
                                return;
                            }
                            conditions.push(`t.${field} ${operator} '${formattedValue}'`);
                        } else {
                            conditions.push(`t.${field} ${operator} '${value}'`);
                        }
                    }
                }
            });

            if (hasError) return;

            if (conditions.length === 0) {
                showToast('请至少输入一个有效的查询条件', 'error');
                return;
            }

            // 获取汇总字段
            const groupByField = document.getElementById('group-by-field').value;
            
            // 构建查询语句
            let query = '';
            if (groupByField) {
                if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                    const selectFields = [
                        't.factory_no',
                        't.passage',
                        ...(selectedColumns.includes('num') ? ['SUM(t.num) as total_num'] : []),
                        ...(selectedColumns.includes('ng_num') ? ['SUM(t.ng_num) as total_ng_num'] : []),
                        ...(selectedColumns.includes('rate') ? ['ROUND((1 - SUM(t.ng_num) / SUM(t.num)) * 100, 2) as rate'] : [])
                    ].filter(Boolean);
                    
                    if (!selectFields.includes('t.factory_no')) selectFields.unshift('t.factory_no');
                    if (!selectFields.includes('t.passage')) selectFields.splice(1, 0, 't.passage');
                    
                    query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                    if (conditions.length > 0) {
                        query += ` WHERE ${conditions.join(' AND ')}`;
                    }
                    query += ` GROUP BY t.factory_no, t.passage`;
                } else {
                    const selectFields = [
                        `t.${groupByField}`,
                        ...(selectedColumns.includes('num') ? ['SUM(t.num) as total_num'] : []),
                        ...(selectedColumns.includes('ng_num') ? ['SUM(t.ng_num) as total_ng_num'] : []),
                        ...(selectedColumns.includes('rate') ? ['ROUND((1 - SUM(t.ng_num) / SUM(t.num)) * 100, 2) as rate'] : [])
                    ].filter(Boolean);
    
                    query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                    if (conditions.length > 0) {
                        query += ` WHERE ${conditions.join(' AND ')}`;
                    }
                    query += ` GROUP BY t.${groupByField}`;
                }
            } else {
                const selectFields = [];
                if (selectedColumns.includes('factory_no')) {
                    selectFields.push('t.factory_no');
                }
                if (selectedColumns.includes('passage')) {
                    selectFields.push('t.passage');
                }
                if (selectedColumns.includes('num')) {
                    selectFields.push('t.num');
                }
                if (selectedColumns.includes('ng_num')) {
                    selectFields.push('t.ng_num');
                }
                if (selectedColumns.includes('rate')) {
                    selectFields.push('ROUND((1 - t.ng_num / t.num) * 100, 2) as rate');
                }
                if (selectedColumns.includes('num1')) {
                    selectFields.push('(SELECT COALESCE(SUM(num), 0) FROM factory_collection1_log WHERE factory_no = t.factory_no AND passage = t.passage AND product_time BETWEEN \'' + conditions.find(c => c.includes('product_time BETWEEN')).split('\'')[1] + '\' AND \'' + conditions.find(c => c.includes('product_time BETWEEN')).split('\'')[3] + '\') as num1');
                }

                if (selectFields.length === 0) {
                    showToast('请至少选择一列显示', 'error');
                    return;
                }

                query = `SELECT ${selectFields.join(', ')} FROM ${tableName} t`;
                if (conditions.length > 0) {
                    query += ` WHERE ${conditions.join(' AND ')}`;
                }
            }

            // 执行查询
            const resultDiv = document.getElementById('query-result');
            const urlParams = new URLSearchParams(window.location.search);
            const dbId = urlParams.get('id');

            // 显示执行中的提示
            const toastPromise = showToast('正在执行追加查询...', 'info', false);
            
            fetch('db_manage.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `action=exec_sql&id=${dbId}&sql=${encodeURIComponent(query)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 将第二次查询的结果转换为Map，用于快速查找
                    const secondDataMap = new Map();
                    data.data.forEach(row => {
                        const key = `${row.factory_no}_${row.passage}`;
                        secondDataMap.set(key, row.total_num || row.num || 0);
                    });

                    // 更新第一次查询的结果，添加num1字段
                    firstQueryResult.forEach(row => {
                        const key = `${row.factory_no}_${row.passage}`;
                        row.num1 = secondDataMap.get(key) || 0;
                    });

                    // 生成表格
                    let html = '<table class="result-table">';
                    
                    // 添加查询条件说明
                    let conditionText = [];
                    document.querySelectorAll('.condition-row').forEach(row => {
                        const field = row.querySelector('.field-select').value;
                        const operator = row.querySelector('.operator-select').value;
                        const value = row.querySelector('.value-input').value;
                        const valueEnd = row.querySelector('.value-input-end').value;
                        
                        if (field && operator) {
                            let condition = translateFieldName(field);
                            if (operator === 'between' && value && valueEnd) {
                                const startDate = new Date(value);
                                const endDate = new Date(valueEnd);
                                const formatDate = (date) => {
                                    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                };
                                condition += ` 介于 ${formatDate(startDate)} 至 ${formatDate(endDate)}`;
                            } else if (operator === 'is null') {
                                condition += ' 为空';
                            } else if (operator === 'is not null') {
                                condition += ' 不为空';
                            } else if (value) {
                                if (field === 'product_time') {
                                    const date = new Date(value);
                                    const formatDate = (date) => {
                                        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
                                    };
                                    condition += ` ${operator} ${formatDate(date)}`;
                                } else {
                                    condition += ` ${operator} ${value}`;
                                }
                            }
                            conditionText.push(condition);
                        }
                    });

                    if (groupByField) {
                        conditionText.push(`按 ${translateFieldName(groupByField)} 汇总`);
                    }

                    // 添加条件说明行
                    if (conditionText.length > 0) {
                        let colspan = selectedColumns.length;
                        if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                            colspan = 2 + (selectedColumns.includes('num1') ? 1 : 0) + (selectedColumns.includes('num') ? 1 : 0) + (selectedColumns.includes('ng_num') ? 1 : 0) + (selectedColumns.includes('rate') ? 1 : 0);
                        } else if (groupByField) {
                            colspan = 1 + (selectedColumns.includes('num1') ? 1 : 0) + (selectedColumns.includes('num') ? 1 : 0) + (selectedColumns.includes('ng_num') ? 1 : 0) + (selectedColumns.includes('rate') ? 1 : 0);
                        }
                        html += '<tr><td colspan="' + colspan + '" style="background-color: #f5f5f5; padding: 8px; font-weight: bold; text-align: left;">';
                        html += '查询条件：' + conditionText.join('，');
                        html += '</td></tr>';
                    }

                    // 添加表头
                    html += '<tr>';
                    if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                        html += `<th>${translateFieldName('factory_no')}</th>`;
                        html += `<th>${translateFieldName('passage')}</th>`;
                        if (selectedColumns.includes('num1')) {
                            html += '<th style="text-align: right;">1#采集数量</th>';
                        }
                        if (selectedColumns.includes('num')) {
                            html += '<th style="text-align: right;">2#采集数量</th>';
                        }
                        if (selectedColumns.includes('ng_num')) {
                            html += '<th style="text-align: right;">不良数量</th>';
                        }
                        if (selectedColumns.includes('rate')) {
                            html += '<th style="text-align: right;">采集率</th>';
                        }
                    } else if (groupByField) {
                        html += `<th>${translateFieldName(groupByField)}</th>`;
                        if (selectedColumns.includes('num1')) {
                            html += '<th style="text-align: right;">1#采集数量</th>';
                        }
                        if (selectedColumns.includes('num')) {
                            html += '<th style="text-align: right;">2#采集数量</th>';
                        }
                        if (selectedColumns.includes('ng_num')) {
                            html += '<th style="text-align: right;">不良数量</th>';
                        }
                        if (selectedColumns.includes('rate')) {
                            html += '<th style="text-align: right;">采集率</th>';
                        }
                    } else {
                        selectedColumns.forEach(col => {
                            let alignStyle = (col === 'num' || col === 'ng_num' || col === 'rate' || col === 'num1') ? ' style="text-align: right;"' : '';
                            let displayName = col === 'num1' ? '1#采集数量' : 
                                           col === 'num' ? '2#采集数量' : 
                                           translateFieldName(col);
                            html += `<th${alignStyle}>${displayName}</th>`;
                        });
                    }
                    html += '</tr>';

                    // 添加数据行
                    if (groupByField === 'factory_no' && selectedColumns.includes('passage')) {
                        const factoryRowSpans = {};
                        firstQueryResult.forEach(row => { 
                            factoryRowSpans[row.factory_no] = (factoryRowSpans[row.factory_no] || 0) + 1; 
                        });
                        
                        let previousFactoryNo = null, 
                            factorySumNum = 0, 
                            factorySumNgNum = 0, 
                            factoryRates = [], 
                            grandSumNum = 0, 
                            grandSumNgNum = 0, 
                            allRates = [],
                            factorySumNum1 = 0,
                            grandSumNum1 = 0;

                        firstQueryResult.sort((a, b) => { 
                            if (a.factory_no < b.factory_no) return -1; 
                            if (a.factory_no > b.factory_no) return 1; 
                            if (a.passage < b.passage) return -1; 
                            if (a.passage > b.passage) return 1; 
                            return 0; 
                        });

                        firstQueryResult.forEach((row, index) => {
                            const currentFactoryNo = row.factory_no;
                            const factoryChanged = previousFactoryNo !== null && currentFactoryNo !== previousFactoryNo;
                            
                            if (factoryChanged) { 
                                html += createSubtotalRow(previousFactoryNo, factorySumNum, factorySumNgNum, factoryRates, selectedColumns, factorySumNum1); 
                                factorySumNum = 0; 
                                factorySumNgNum = 0; 
                                factoryRates = []; 
                                factorySumNum1 = 0;
                            }

                            html += '<tr>';
                            if (currentFactoryNo !== previousFactoryNo) { 
                                const factoryValue = dictionary.factory_codes ? dictionary.factory_codes[currentFactoryNo] || currentFactoryNo : currentFactoryNo; 
                                const rowspan = factoryRowSpans[currentFactoryNo] || 1; 
                                html += `<td rowspan="${rowspan}">${factoryValue || ''}</td>`; 
                            }

                            html += `<td>${row.passage || ''}</td>`;
                            
                            if (selectedColumns.includes('num1')) { 
                                const num1 = parseInt(row.num1) || 0; 
                                html += `<td style="text-align: right;">${num1}</td>`; 
                                factorySumNum1 += num1;
                                grandSumNum1 += num1;
                            }

                            if (selectedColumns.includes('num')) { 
                                const num = parseInt(row.total_num) || 0; 
                                html += `<td style="text-align: right;">${num}</td>`; 
                                factorySumNum += num; 
                                grandSumNum += num; 
                            }

                            if (selectedColumns.includes('ng_num')) { 
                                const ngNum = parseInt(row.total_ng_num) || 0; 
                                html += `<td style="text-align: right;">${ngNum}</td>`; 
                                factorySumNgNum += ngNum; 
                                grandSumNgNum += ngNum; 
                            }

                            if (selectedColumns.includes('rate')) { 
                                const rateValue = parseFloat(row.rate) || 0; 
                                html += `<td style="text-align: right;" class="rate-cell">${rateValue.toFixed(2)}%</td>`; 
                                factoryRates.push(rateValue); 
                                allRates.push(rateValue); 
                            }

                            html += '</tr>';
                            previousFactoryNo = currentFactoryNo;

                            if (index === firstQueryResult.length - 1) { 
                                html += createSubtotalRow(currentFactoryNo, factorySumNum, factorySumNgNum, factoryRates, selectedColumns, factorySumNum1); 
                            }
                        });

                        html += createGrandTotalRow(grandSumNum, grandSumNgNum, allRates, selectedColumns, grandSumNum1);
                    } else if (groupByField) {
                        let totalNum = 0, totalNgNum = 0, totalNum1 = 0;
                        firstQueryResult.forEach(row => {
                            html += '<tr>';
                            const fieldValue = dictionary.factory_codes && groupByField === 'factory_no' ? dictionary.factory_codes[row[groupByField]] : row[groupByField];
                            html += `<td>${fieldValue || ''}</td>`;
                            
                            if (selectedColumns.includes('num1')) { 
                                const num1 = parseInt(row.num1) || 0; 
                                html += `<td style="text-align: right;">${num1}</td>`; 
                                totalNum1 += num1;
                            }

                            if (selectedColumns.includes('num')) { 
                                const num = parseInt(row.total_num) || 0; 
                                html += `<td style="text-align: right;">${num}</td>`; 
                                totalNum += num; 
                            }

                            if (selectedColumns.includes('ng_num')) { 
                                const ngNum = parseInt(row.total_ng_num) || 0; 
                                html += `<td style="text-align: right;">${ngNum}</td>`; 
                                totalNgNum += ngNum; 
                            }

                            if (selectedColumns.includes('rate')) { 
                                html += `<td style="text-align: right;" class="rate-cell">${row.rate || '0.00'}%</td>`; 
                            }

                            html += '</tr>';
                        });

                        const totalRate = totalNum > 0 ? ((1 - totalNgNum / totalNum) * 100).toFixed(2) : '0.00';
                        html += '<tr class="factory-summary" style="font-weight:bold; background-color: #d6e4ff !important;">';
                        html += '<td>总计</td>';
                        if (selectedColumns.includes('num1')) { 
                            html += `<td style="text-align: right;">${totalNum1}</td>`; 
                        }
                        if (selectedColumns.includes('num')) { 
                            html += `<td style="text-align: right;">${totalNum}</td>`; 
                        }
                        if (selectedColumns.includes('ng_num')) { 
                            html += `<td style="text-align: right;">${totalNgNum}</td>`; 
                        }
                        if (selectedColumns.includes('rate')) { 
                            html += `<td style="text-align: right;" class="rate-cell">${totalRate}%</td>`; 
                        }
                        html += '</tr>';
                    } else {
                        firstQueryResult.forEach(row => {
                            html += '<tr>';
                            selectedColumns.forEach(col => {
                                let value = row[col];
                                let alignStyle = (col === 'num' || col === 'ng_num' || col === 'rate' || col === 'num1') ? ' style="text-align: right;"' : '';
                                let className = (col === 'rate') ? ' class="rate-cell"' : '';
                                if (col === 'factory_no' && dictionary.factory_codes) {
                                    value = dictionary.factory_codes[value] || value;
                                }
                                if (col === 'num' || col === 'ng_num' || col === 'num1') {
                                    value = value || 0;
                                }
                                if (col === 'rate') {
                                    value = value || '0.00';
                                    value += '%';
                                }
                                html += `<td${alignStyle}${className}>${value || ''}</td>`;
                            });
                            html += '</tr>';
                        });
                    }

                    html += '</table>';
                    resultDiv.innerHTML = html;
                    hideToast();
                    showToast('追加查询完成', 'success', true);

                    // 添加悬停效果
                    const tableBody = resultDiv.querySelector('.result-table tbody');
                    if (tableBody) {
                        const rows = tableBody.querySelectorAll('tr');
                        rows.forEach(row => {
                            row.dataset.originalBg = window.getComputedStyle(row).backgroundColor;
                            
                            row.addEventListener('mouseover', () => {
                                if (row.classList.contains('factory-summary')) {
                                    row.style.backgroundColor = '#cce5ff';
                                } else {
                                    row.style.backgroundColor = '#e6f4ff';
                                }
                                row.style.cursor = 'pointer';
                            });
                            
                            row.addEventListener('mouseout', () => {
                                row.style.backgroundColor = row.dataset.originalBg || '';
                                row.style.cursor = 'default';
                            });
                        });
                    }

                    // 添加追加查询按钮
                    const appendBtn = document.getElementById('append-query-btn');
                    if (appendBtn) {
                        appendBtn.disabled = true;
                        appendBtn.style.backgroundColor = '#ccc';
                        appendBtn.style.cursor = 'not-allowed';
                        appendBtn.title = '已追加，无法再次追加';
                    }

                } else {
                    hideToast();
                    showToast(data.message, 'error', true);
                }
                })
                .catch(error => {
                hideToast();
                showToast('追加查询失败：' + error.message, 'error', true);
                });
        }
    </script>
</body>
</html>